import axios from "axios";

const api_url = (import.meta.env.VITE_SEREVER_API as string) || "/api";

const api = axios.create({
  baseURL: api_url,
});

api.interceptors.request.use(
  (config: any) => {
    if (localStorage.token) {
      config.headers.Authorization =
        "Bearer " + localStorage.getItem("token") || "";
    }
    return config;
  },
  (e) => {
    return Promise.reject(e);
  }
);

api.interceptors.response.use(
  (res) => res,
  (e) => {
    if (e.response.status == 401) {
      localStorage.clear();
    }
    return Promise.reject(e);
  }
);

export { api };
